import React from 'react';
//引入umi的路由事件
import { history } from 'umi';
// import Style from '@/scss/login.scss'
import Style from '@/scss/register.scss';
import axios from 'axios';
import EmilUtils from '../store';
const { authEmil, sendEmil } = EmilUtils;
import JWT from '@/utils/jwtutil';
import Tools from '@/utils/tools';
const { generateUUID, generateAuth } = Tools;
import CONST from '@/inits/consts';
const LOGINDATA = CONST.LOGINDATA;
const out = () => {
  history.push('/');
};
//注册事件
function Register() {
  const [name, setName] = React.useState('');
  const [pwd, setPwd] = React.useState('');
  const [emil, setEmil] = React.useState('');
  const [auth, setAuth] = React.useState('');

  const handleRegister = async () => {
    if (!name || !pwd || !emil || !auth) {
      alert('填写项不可为空');
      return;
    }
    // if(auth) ;
    let result = await JWT.verifysync(
      localStorage.getItem('uuth'),
      LOGINDATA.KEY,
    );
    //校验失败则直接返回,不继续进行
    if (result.err) {
      alert('校验码已经过期,请重新发送');
      return;
    } else if (result.auth != auth) {
      alert('验证码输入错误');
      return;
    } else if (result.name != name || result.emil != emil) {
      alert('信息不匹配!可能您在验证期间修改了用户信息');
      return;
    }
    console.log('xxxxxx');
    //  if(result)
    //拼凑新用户模板
    let user = {
      username: name,
      password: pwd,
      Emil: emil,
      id: generateUUID(),
      head: 'index.png',
      todos: '',
    };
    let flag = await axios({
      url: 'http://localhost:53000/users',
    }).then((v) => {
      if (v.data.filter((v) => v.username == name).length > 0) return false;
      else return true;
    });
    if (!flag) alert('该用户名已被占用');
    else {
      axios({
        url: 'http://localhost:53000/users',
        method: 'post',
        data: user,
      }).then((v) => {
        alert('注册成功,返回');
        history.push('/');
      });
    }
  };

  const handleAuthEmil = async () => {
    //生成一个随机id用作发送验证码发送
    let uuth = generateAuth();
    //将生成验证码与邮箱、用户名存入数据库,且设置过期时间为5分钟,用作输入验证码时候校验使用
    //为什么要存入用户名和邮箱? 如果我发送验证码后 再修改了用户名与邮箱,那么不再进行二次验证会导致邮箱被恶意绑定
    let jwt_uuth = JWT.sign({ name, emil, auth: uuth }, LOGINDATA.KEY, 300);
    localStorage.setItem('uuth', jwt_uuth);

    //首先校验邮箱格式,错误则直接中断
    if (!authEmil(emil)) return;
    //将校验码发送给指定邮箱,
    let result = await sendEmil(
      emil,
      '代办事件注册验证',
      '这是您的验证码,请在有效期内使用',
      `这是您的验证码,请在有效期内使用: <i style='color:red'>${uuth}</i>`,
    );
    if (result.httpCode != 200) alert('请勿多次操作,请等待一会后重新发送');
    else alert(result.message);
  };

  return (
    <div className={Style.zhuce}>
      <div className={Style.center}>
        <h1>欢迎注册待办备忘录</h1>
        <div className={Style.z_input}>
          <input
            onChange={(e: any) => setName(e.target.value.trim())}
            type="text"
            placeholder="账号"
          />
        </div>
        <div className={Style.z_input}>
          <input
            onChange={(e: any) => setPwd(e.target.value.trim())}
            type="text"
            placeholder="密码"
          />
        </div>
        <div className={Style.z_input}>
          <input
            onChange={(e: any) => setEmil(e.target.value.trim())}
            type="text"
            placeholder="邮箱"
          />
          <div className={Style.z_input_send} onClick={(e) => handleAuthEmil()}>
            <i>发送验证码</i>
          </div>
        </div>
        <div className={Style.z_input}>
          <input
            onChange={(e: any) => setAuth(e.target.value.trim())}
            type="text"
            placeholder="请输入验证码"
          />
        </div>
        <button onClick={() => handleRegister()}>立即注册</button>
        <button style={{ marginTop: '10px' }} onClick={() => out()}>
          返回登录
        </button>
      </div>
    </div>
  );
}

export default Register;
